package com.biz.primus.ms.payment.dao.repository;

import com.biz.primus.base.enums.PaymentStatusEnum;
import com.biz.primus.ms.base.jpa.repository.CommonJpaRepository;
import com.biz.primus.ms.payment.dao.po.PaymentOrder;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.sql.Timestamp;
import java.util.List;

/**
 * Created by defei on 9/22/17.
 */
public interface PaymentOrderRepository extends CommonJpaRepository<PaymentOrder, Long>, PaymentOrderDao {

    @Modifying
    @Query("update PaymentOrder po set po.paymentStatus = ?2 where po.id = ?1")
    void updatePaymentState(Long id, PaymentStatusEnum payed);

    @Modifying
    @Query("update PaymentOrder po set po.paymentStatus = PAID, po.tradeNo = ?2, po.paySuccessTime = ?3 where po.id = ?1 and po.paymentStatus = CREATE_PAYMENT")
    Integer confirmPaid(Long id, String tradeNo, Timestamp paySuccessTime);

    @Modifying
    @Query("update PaymentOrder po set po.paymentStatus = REFUNDING, po.mchRefundNo = ?2, po.refundSuccessTime = ?3 where po.id = ?1 and po.paymentStatus = PAID")
    Integer confirmRefunding(Long id, String refundNo, Timestamp timestamp);

    @Modifying
    @Query("update PaymentOrder po set po.paymentStatus = REFUNDED, po.mchOrderNo = ?2, po.refundSuccessTime = ?3 where po.id = ?1 and (po.paymentStatus = PAID OR po.paymentStatus = REFUNDING)")
    Integer confirmRefunded(Long id, String refundNo, Timestamp timestamp);

    List<PaymentOrder> findByMchIdAndMchOrderNoOrderByCreateTimestampDesc(String mchId, String orderId);

    @Modifying
    @Query("UPDATE PaymentOrder po SET po.paymentStatus = DISCARD WHERE po.mchId = :mchId and po.mchOrderNo = :mchOrderNo and po.paymentStatus <> PAID")
    Integer makeExistPaymentOrderToDiscardIfNotPaid(@Param("mchId") String mchId, @Param("mchOrderNo") String mchOrderNo);

    @Modifying
    @Query("update PaymentOrder po set po.tradeNo = ?2 where po.id = ?1")
    Integer bindTradeNo(Long paymentOrderId, String tradeNo);

    /**
     * 根据订单编号获取支付单，在支付中心只接入一个商家是有效
     *
     * @param mchOrderNo 订单编号
     * @return List<PaymentOrder>
     */
    List<PaymentOrder> findByMchOrderNoOrderByCreateTimestampDesc(String mchOrderNo);
}
